import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author GAX
 * @date 2025-09-05
 */
public class JucProComsumerDemo {
    public static void main(String[] args) {
        JucAirCondition jucAirCondition = new JucAirCondition();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    jucAirCondition.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    jucAirCondition.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A2").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    jucAirCondition.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    jucAirCondition.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B2").start();
    }
}

// 使用 JUC 的 Lock + Condition 实现生产者-消费者模式
class JucAirCondition {
    private int number = 0;

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    // 操作
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            // 判断
            while (number != 0) {
                condition.await();
            }
            // 干活
            System.out.println(Thread.currentThread().getName() + "\t" + (++number));
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            // 判断
            while (number == 0) {
                condition.await();
            }
            // 干活
            System.out.println(Thread.currentThread().getName() + "\t" + (--number));
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}